﻿using System;
using System.Collections.Generic;
using System.Web.Mvc;
using Xenta.Utils;
using Xenta.Attributes;
using Xenta.Web.Controllers;

namespace Xenta.Web.Areas.Commerce.Controllers
{
    [Authenticate, InRole("ADMIN")]
    public sealed class InvoiceController : ExtController
    {
        #region GET/POST Actions

        [HttpGet]
        public ActionResult Index()
        {
            return View();
        }

        [HttpGet]
        public ActionResult GoTo(int? id, string guid)
        {
            if(!id.HasValue)
            {
                dynamic m = null;
                if(!String.IsNullOrWhiteSpace(guid))
                {
                    m = Svc.ProcessOperation("GetInvoiceByGuid", new
                    {
                        Guid = guid.ParseAs<Guid>()
                    });
                }
                if(m == null)
                    return HttpNotFound();
                id = JDM.Int32(m.EntityID);
            }
            return RedirectToAction(Loc.Act("Edit").Set(new
            {
                id
            }));
        }

        [HttpGet, RestoreState]
        public ActionResult Create()
        {
            return View();
        }

        [HttpPost, PersistState]
        public ActionResult Place(int orderID,
            string total,
            string issuedOn)
        {
            try
            {
                var m = Svc.ProcessOperation("PlaceInvoice", new
                {
                    OrderID = orderID,
                    Total = Svc.Price(total),
                    IssuedOn = Svc.DateTime(issuedOn),
                });
                return RedirectToAction(Loc.Act("Edit").Set(new
                {
                    id = JDM.Int32(m.EntityID)
                }));
            }
            catch(Exception ex)
            {
                ModelState.AddModelError("API", ex);
            }
            return RedirectToAction(Loc.Act("Create"));
        }

        [HttpGet, RestoreState]
        public ActionResult Edit(int id)
        {
            var m = Svc.ProcessOperation("GetInvoice", new
            {
                EntityID = id,
                Fetch = "Entire"
            }, new
            {
                DisclosureLevel = "Base"
            });
            if(m == null)
                return HttpNotFound();
            return View(m);
        }

        [HttpPost, PersistState]
        public ActionResult Update(int id, 
            int orderID,
            string total,
            string paidAmount,
            string refundAmount,
            string issuedOn,
            string[] flags)
        {
            try
            {
                Svc.ProcessOperation("UpdateInvoice", new
                {
                    EntityID = id,
                    OrderID = orderID,
                    Total = Svc.Price(total),
                    PaidAmount = Svc.Price(paidAmount),
                    RefundAmount = Svc.Price(refundAmount),
                    IssuedOn = Svc.DateTime(issuedOn),
                    Flags = flags.Merge(",")
                });
            }
            catch(Exception ex)
            {
                ModelState.AddModelError("API", ex);
            }

            return RedirectToAction(Loc.Act("Edit").Set(new
            {
                id
            }));
        }

        [HttpGet, PersistState]
        public ActionResult Delete(int id)
        {
            try
            {
                Svc.ProcessOperation("DeleteInvoice", new
                {
                    EntityID = id
                });
                return RedirectToAction(Loc.Act("Index"));
            }
            catch(Exception ex)
            {
                ModelState.AddModelError("API", ex);
            }
            return RedirectToAction(Loc.Act("Edit").Set(new
            {
                id
            }));
        }

        [HttpGet, PersistState]
        public ActionResult Issue(int id)
        {
            try
            {
                Svc.ProcessOperation("IssueInvoice", new
                {
                    EntityID = id
                });
            }
            catch(Exception ex)
            {
                ModelState.AddModelError("API", ex);
            }
            return RedirectToAction(Loc.Act("Edit").Set(new
            {
                id
            }));
        }

        [HttpGet, PersistState]
        public ActionResult Cancel(int id)
        {
            try
            {
                Svc.ProcessOperation("CancelInvoice", new
                {
                    EntityID = id
                });
            }
            catch(Exception ex)
            {
                ModelState.AddModelError("API", ex);
            }
            return RedirectToAction(Loc.Act("Edit").Set(new
            {
                id
            }));
        }

        #endregion

        #region AJAX Actions

        [HttpPost]
        public ActionResult Grid(int? page, 
            int? rows, 
            string sord, 
            string sidx,
            int? orderID,
            int? customerID,
            string createdFrom,
            string createdTo,
            string flagMask)
        {
            page = page.HasValue ? page.Value - 1 : 0;
            rows = rows.HasValue ? rows.Value : 30;
            sord = sord.Equals("desc") ? "Descending" : "Ascending";

            var m = Svc.ProcessOperation("SearchInvoices", new
            {
                OrderID = orderID,
                CustomerID = customerID,
                FlagMask = flagMask,
                CreatedFrom = String.IsNullOrWhiteSpace(createdFrom)
                    ? (DateTime?)null
                    : Svc.DateTime(createdFrom),
                CreatedTo = String.IsNullOrWhiteSpace(createdTo)
                    ? (DateTime?)null
                    : Svc.DateTime(createdTo),
                Index = page * rows,
                Count = rows,
                SortBy = new[] 
                {
                    sidx
                },
                SortDir = sord
            }, new
            {
                DisclosureLevel = "Base"
            });
            var data = new List<Object>();

            foreach(var i in m.Items)
            {
                string status = String.Empty;

                if(JDM.HasFlags(i.Flags, "Canceled"))
                    status = Svc.Translate(Res.In("API").Of("Enum").Of("InvoiceFlags").Name("Canceled"));
                else if(JDM.HasFlags(i.Flags, "Pending"))
                    status = Svc.Translate(Res.In("API").Of("Enum").Of("InvoiceFlags").Name("Pending"));
                else if(JDM.HasFlags(i.Flags, "Issued"))
                    status = Svc.Translate(Res.In("API").Of("Enum").Of("InvoiceFlags").Name("Issued"));
                else if(JDM.HasFlags(i.Flags, "Paid"))
                    status = Svc.Translate(Res.In("API").Of("Enum").Of("InvoiceFlags").Name("Paid"));

                data.Add(new[] { 
                    JDM.Int32(i.EntityID),
                    JDM.Int32(i.Order.EntityID),
                    Svc.Price((decimal)JDM.Decimal(i.Total)),
                    Svc.Price((decimal)JDM.Decimal(i.PaidAmount)),
                    Svc.Price((decimal)JDM.Decimal(i.RefundAmount)),
                    status,
                    Svc.DateTime((DateTime)JDM.DateTime(i.IssuedOn)),
                    Svc.DateTime((DateTime)JDM.DateTime(i.CreatedOn))
                });
            }

            return Json(new
            {
                pageIndex = page + 1,
                pageCount = Math.Ceiling(JDM.Double(m.TotalCount) / rows),
                totalCount = JDM.Int64(m.TotalCount),
                data = data.ToArray()
            });
        }

        #endregion
    }
}
